package conf

import (
	"context"
	"flag"
	"fmt"
	"os"
)

var usageStr = `
Usage: instance [options] <subject>

Options:
	-c, --config   <config_file>            config file path

`

var ctxGlobal context.Context

// GetCtx get global context
func GetCtx() context.Context {
	return ctxGlobal
}

// GetConf get config
func GetConf() *Config {
	return config
}

var config = &Config{
	App: &App{
		Name:      "databox-broker",
		HTTPPort:  34543,
		ENV:       "dev",
		Debug:     false,
		DebugPort: 9999,
	},
	Log: &Log{},
	Dao: &Dao{
		ResCenter: &ResCenter{},
	},
}

// Config defination
type Config struct {
	App *App `json:"app" toml:"app"`
	Log *Log `json:"log" toml:"log"`
	Dao *Dao `json:"dao" toml:"dao"`
}

// App config
type App struct {
	Name      string `json:"name" toml:"name"`
	HTTPPort  int    `json:"http_port" toml:"http_port"`
	ENV       string `json:"env" toml:"env"`
	Debug     bool   `json:"debug" toml:"debug"`
	DebugPort int    `json:"debug_port" toml:"debug_port"`
}

// Log config
type Log struct {
	Path string `json:"path" toml:"path"`
}

// Dao conf
type Dao struct {
	ResCenter *ResCenter `json:"rescenter" toml:"rescenter"`
}

// ResCenter conf
type ResCenter struct {
	Host string `json:"host" toml:"host"`
	Port int    `json:"port" toml:"port"`
}

func usage() {
	fmt.Println(usageStr)
	os.Exit(1)
}

// Init init config
func Init(ctx context.Context) {
	ctxGlobal = ctx
	var fConf string
	flag.StringVar(&fConf, "conf", "", "config file")
	flag.StringVar(&fConf, "config", "", "config file")
	flag.Parse()

	if fConf == "" {
		//usage()
		fConf = "conf/conf.dev.toml"
	}

	//if _, err := toml.DecodeFile(fConf, &config); err != nil {
	//	fmt.Println(err)
	//	os.Exit(1)
	//}
	config.App.Name = "equipment"
	config.App.ENV = "dev"
	config.App.HTTPPort = 3454
	config.App.DebugPort = 9999
	config.Log.Path = "./var/log"
	config.Dao.ResCenter.Host = "127.0.0.1"
	config.Dao.ResCenter.Port = 8087

	if debug, ok := os.LookupEnv("APP_DEBUG"); ok && debug == "on" {
		config.App.Debug = true
	}

	if env, ok := os.LookupEnv("APP_ENV"); ok && env != "" {
		config.App.ENV = env
	}

}
